package com.jrapider;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.kaptcha.exception.KaptchaException;
import com.baomidou.kaptcha.exception.KaptchaIncorrectException;
import com.baomidou.kaptcha.exception.KaptchaNotFoundException;
import com.baomidou.kaptcha.exception.KaptchaTimeoutException;
import com.jrapider.exception.TransRollbackException;
import com.jrapider.om.JSONResult;
import lombok.extern.log4j.Log4j2;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @Auther: hxs
 * @Date: 2018/12/28
 * @Description:
 */
@ControllerAdvice
@Log4j2
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    public String exception(HttpServletRequest request, HttpServletResponse response, Exception exception) throws IOException {
        log.error(exception.getMessage(),exception);
        if(isAjaxRequest(request)){
            writeJson(response,JSONResult.newBuilder().fail("未知异常:"+exception.getMessage()).build());
            return null;
        }else{
            return "500";
        }
    }
    @ExceptionHandler(TransRollbackException.class)
    public String transRollbackException(HttpServletRequest request, HttpServletResponse response, Exception exception) throws IOException {
        log.error(exception.getMessage(),exception);
        if(isAjaxRequest(request)){
            writeJson(response,JSONResult.newBuilder().fail("数据处理异常:"+exception.getMessage()).build());
            return null;
        }else{
            return "500";
        }
    }
    @ExceptionHandler(DuplicateKeyException.class)
    public String duplicateKeyException(HttpServletRequest request, HttpServletResponse response, Exception exception) throws IOException {
        log.error(exception.getMessage(),exception);
        if(isAjaxRequest(request)){
            writeJson(response,JSONResult.newBuilder().fail("数据重复:"+exception.getMessage()).build());
            return null;
        }else{
            return "500";
        }
    }

    @ExceptionHandler(value = KaptchaException.class)
    public String kaptchaExceptionHandler(HttpServletRequest request, HttpServletResponse response,KaptchaException kaptchaException) throws IOException {
        if (kaptchaException instanceof KaptchaIncorrectException) {
            writeJson(response,JSONResult.newBuilder().fail("验证码不正确").build());
        } else if (kaptchaException instanceof KaptchaNotFoundException) {
            writeJson(response,JSONResult.newBuilder().fail("验证码未找到").build());
        } else if (kaptchaException instanceof KaptchaTimeoutException) {
            writeJson(response,JSONResult.newBuilder().fail("验证码过期").build());
        } else {
            writeJson(response,JSONResult.newBuilder().fail("验证码渲染失败").build());
        }
        return null;

    }
    private void writeJson(HttpServletResponse resp, JSONObject data) throws IOException {
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("application/json; charset=utf-8");
        PrintWriter writer = resp.getWriter();
        writer.write(data.toJSONString());

    }

    private static boolean isAjaxRequest(HttpServletRequest request) {
        String requestedWith = request.getHeader("x-requested-with");
        if (requestedWith != null && requestedWith.equalsIgnoreCase("XMLHttpRequest")) {
            return true;
        } else {
            return false;
        }
    }
}
